package org.p2psimulator.entity.protocol.hibrid.eigentrust.eigencycles;

import java.util.Collection;

import org.p2psimulator.entity.Id;
import org.p2psimulator.entity.protocol.ProtocolCycle;
import org.p2psimulator.entity.reputation.Reputation;
import org.p2psimulator.entity.reputation.ReputationManager;
import org.p2psimulator.entity.reputation.ReputationRepository;
import org.p2psimulator.entity.reputation.ReputationRepositoryTypes;
import org.p2psimulator.entity.reputation.hibrid.EigenReputation;
import org.p2psimulator.exceptions.ReputationRepositoryException;
import org.p2psimulator.engine.Environment;

public abstract class EigenCycle extends ProtocolCycle {

    public EigenCycle(Environment env, int transId) {
        super(env, transId);
    }

    public void normalizeReputationValue(Id raterId, Id serventId) {
        // normalização

        ReputationManager manager = env.getReputationManager();
        ReputationRepository rep = manager.getReputationRepository(ReputationRepositoryTypes.REP_SERVENT_REPOSITORY);

        Reputation serventRep = null;
        try {
            serventRep = rep.getLocalReputation(raterId, serventId);
        } catch (ReputationRepositoryException ex) {
        }
        if (serventRep == null) {
            serventRep = new EigenReputation(0, 0, raterId, serventId);
            rep.addReputation(raterId, serventRep);
        }
        Collection<Reputation> avarage = rep.getAllReputations(raterId);
        double sum = 1;
        for (Reputation r : avarage) {
            sum += r.getNormalReputation()>0?r.getNormalReputation():0;
        }

        double normal = serventRep.getNormalReputation()>0?serventRep.getNormalReputation():0;

        double normalizedValue = normal / sum;
        serventRep.setNormalizedValue(normalizedValue);
    }
}
